﻿
namespace GloboTicketAdmin.API.Controllers
{
    using GloboTicketAdmin.API.Common;
    using GloboTicketAdmin.API.Models;
    using GloboTicketAdmin.API.Models.Domain;
    using GloboTicketAdmin.API.Models.Dto;
    using GloboTicketAdmin.API.Services.IService;
    using Mapster;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    using System.Net.Sockets;

    [ApiController]
    [Route("api/events")]
    public class EventsController : ControllerBase
    {
        private readonly ILogger<EventsController> _logger;
        private readonly IEventService _eventService;
        private readonly ICategoryService _categoryService;

        public EventsController(IEventService eventService,ICategoryService categoryService, ILogger<EventsController> logger)
        {
            _eventService = eventService;
            _categoryService = categoryService;
            _logger = logger;
        }

        // ... 其他接口

        [HttpPost("add")]
        public ActionResult<ApiResponse<EventModel>> AddEvent([FromBody] EventFormDto dto)
        {
            try
            {
                _logger.LogInformation("Adding new event: {@EventDto}", dto);
                var ticket = _categoryService.GetId(dto.CategoryId);
                var model = new EventModel
                {
                    Name = dto.Name ?? string.Empty,
                    //ImageUrl = dto.Poster,
                    ImageUrl = ImageGenerator.GetRandomImageUrl(300, 400, ticket?.Lable ?? "nature"),
                    Price = dto.Price ?? 0,
                    StartTime = dto.StartTime ?? DateTime.Now,
                    EndTime = dto.EndTime ?? DateTime.Now,
                    Artists = dto.Artists,
                    Description = dto.Description,
                    EventStatus = dto.EventStatus ?? EventStatusModel.OnSale,
                    CategoryId = dto?.CategoryId ?? Guid.Empty
                };
                var result = _eventService.InsertEvent(model);
                if (result > 0)
                {
                    return ApiResponse<EventModel>.SuccessResult(model, "添加成功");
                }
                return ApiResponse<EventModel>.ErrorResult("添加失败");
            }
            catch (Exception ex)
            {
                return ApiResponse<EventModel>.ErrorResult($"服务器错误：{ex.Message}");
            }
           
        }

        [HttpPost()]
        public ActionResult<ApiResponse<EventModel>> CreateEvent([FromBody] EventModel model)
        {
            try
            {
                if (model?.Category != null)
                { model.CategoryId = model.Category.Id; }
                if (string.IsNullOrEmpty(model?.ImageUrl))
                { model.ImageUrl = ImageGenerator.GetRandomImageUrl(300, 400, "nature"); }
                _logger.LogInformation($"Adding new event: {JsonConvert.SerializeObject(model)}");
                var result = _eventService.InsertEvent(model);
                if (result > 0)
                {
                    return ApiResponse<EventModel>.SuccessResult(model, "添加成功");
                }
                return ApiResponse<EventModel>.ErrorResult("添加失败");
            }
            catch (Exception ex)
            {
                return ApiResponse<EventModel>.ErrorResult($"服务器错误：{ex.Message}");
            }

        }

        [HttpDelete("{id}")]
        public ActionResult<ApiResponse<EventDto>> DeleteEvent(Guid id)
        {
            try
            {
                var existingEvent = _eventService.GetEventById(id);
                if (existingEvent == null)
                {
                    return ApiResponse<EventDto>.ErrorResult("Event not found");
                }
                var result = _eventService.DeleteEventById(id);
                if (result > 0)
                {
                    var dto = existingEvent.Adapt<EventDto>();
                    return ApiResponse<EventDto>.SuccessResult(dto, "删除成功");
                }
                return ApiResponse<EventDto>.ErrorResult("删除失败");
            }
            catch (Exception ex)
            {
                return ApiResponse<EventDto>.ErrorResult($"服务器错误：{ex.Message}");
            }

        }

        [HttpGet("{id}")]
        public ActionResult<ApiResponse<EventDto>> GetEvent(Guid id)
        {
            try
            {
                var _event = _eventService.GetEventById(id);
                if (_event == null)
                {
                    return ApiResponse<EventDto>.ErrorResult("未找到指定的票务信息");
                }
                var eventDto = _event.Adapt<EventDto>();
                return ApiResponse<EventDto>.SuccessResult(eventDto);
            }
            catch (Exception ex)
            {
                return ApiResponse<EventDto>.ErrorResult($"服务器错误：{ex.Message}");
            }
        }

        [HttpGet()]
        public ActionResult<ApiResponse<List<EventDto>>> GetAll()
        {
            var _events = _eventService.GetAllEvents();
            var eventDtos = _events.Adapt<List<EventDto>>();

            return ApiResponse<List<EventDto>>.SuccessResult(eventDtos);
        }
        /// <summary>
        /// 修改票务信息
        /// </summary>
        /// <param name="id">票务ID</param>
        /// <param name="model">修改的票务数据</param>
        [HttpPut("{id}")]
        public ActionResult<ApiResponse<EventModel>> EditEvent(Guid id, [FromBody] EventModel model)
        {
            try
            {
                var ticket = _eventService.GetEventById(id);

                if (ticket == null)
                {
                    return ApiResponse<EventModel>.ErrorResult("未找到指定的票务信息");
                }

                // 3. 数据验证
                if (model.StartTime > model.EndTime)
                {
                    return ApiResponse<EventModel>.ErrorResult("开始时间不能晚于结束时间");
                }

                if (model.Price <= 0)
                {
                    return ApiResponse<EventModel>.ErrorResult("票价必须大于0");
                }

                if ( model.Stock < 0)
                {
                    return ApiResponse<EventModel>.ErrorResult("库存不能为负数");
                }

                // 4. 处理库存变更（如果需要记录库存日志，这里可以添加逻辑）
                bool stockChanged = false;
                if (model.Stock != ticket.Stock)
                {
                    stockChanged = true;
                    // 可以在这里添加库存变更记录逻辑
                }
                if (string.IsNullOrEmpty(model.ImageUrl))
                { model.ImageUrl = ImageGenerator.GetRandomImageUrl(300, 400, ticket.Category?.Lable ?? "nature"); }
                if (model?.Category != null)
                { model.CategoryId = model.Category.Id; }
              
                // 6. 执行更新
                var affectedRows = _eventService.UpdateEventById(model);

                if (affectedRows > 0)
                {
                    // 7. 查询更新后的完整信息
                    //var updatedTicket = _eventService.GetEventById(id);
                    return ApiResponse<EventModel>.SuccessResult(model, "票务信息更新成功");
                }
                else
                {
                    return ApiResponse<EventModel>.ErrorResult("票务信息更新失败，请重试");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse<EventModel>.ErrorResult($"服务器错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 修改票务信息
        /// </summary>
        /// <param name="id">票务ID</param>
        /// <param name="dto">修改的票务数据</param>
        [HttpPut("update/{id}")]
        public ActionResult<ApiResponse<EventDto>> UpdateEvent(Guid id, [FromBody] EventFormDto dto)
        {
            try
            {
                var ticket = _eventService.GetEventById(id);

                if (ticket == null)
                {
                    return ApiResponse<EventDto>.ErrorResult("未找到指定的票务信息");
                }

                // 3. 数据验证
                if (dto.StartTime.HasValue && dto.EndTime.HasValue && dto.StartTime > dto.EndTime)
                {
                    return ApiResponse<EventDto>.ErrorResult("开始时间不能晚于结束时间");
                }

                if (dto.Price.HasValue && dto.Price <= 0)
                {
                    return ApiResponse<EventDto>.ErrorResult("票价必须大于0");
                }

                if (dto.Stock.HasValue && dto.Stock < 0)
                {
                    return ApiResponse<EventDto>.ErrorResult("库存不能为负数");
                }

                // 4. 处理库存变更（如果需要记录库存日志，这里可以添加逻辑）
                bool stockChanged = false;
                if (dto.Stock.HasValue && dto.Stock.Value != ticket.Stock)
                {
                    stockChanged = true;
                    // 可以在这里添加库存变更记录逻辑
                }

                // 5. 更新票务信息
                var updateObj = new EventModel
                {
                    Id = id, // 必须指定ID
                    Name = string.IsNullOrEmpty(dto.Name) ? ticket.Name : dto.Name,
                    ImageUrl = ImageGenerator.GetRandomImageUrl(300, 400, ticket.Category?.Lable ?? "nature"), 
                    Description = dto.Description ?? ticket.Description,
                    Price = dto.Price ?? ticket.Price,
                    Stock = dto.Stock ?? ticket.Stock,
                    Artists = dto.Artists ?? ticket.Artists,
                    StartTime = dto.StartTime ?? ticket.StartTime,
                    EndTime = dto.EndTime ?? ticket.EndTime,
                    EventStatus = dto.EventStatus ?? ticket.EventStatus,
                    CreateTime = ticket.CreateTime, // 保持创建时间不变
                    UpdateTime = DateTime.Now // 更新时间为当前时间
                };

                // 6. 执行更新
                var affectedRows = _eventService.UpdateEventById(updateObj);

                if (affectedRows > 0)
                {
                    // 7. 查询更新后的完整信息
                    var updatedTicket = _eventService.GetEventById(id);

                    // 8. 转换为响应DTO
                    var updatedDto = updatedTicket.Adapt<EventDto>();
                    return ApiResponse<EventDto>.SuccessResult(updatedDto, "票务信息更新成功");
                }
                else
                {
                    return ApiResponse<EventDto>.ErrorResult("票务信息更新失败，请重试");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse<EventDto>.ErrorResult($"服务器错误：{ex.Message}");
            }
        }


        [HttpPut("{id}/status")]
        public ActionResult<ApiResponse<int>> UpdateStatus(Guid id, [FromBody] EventStatusModel status)
        {
            var iret = _eventService.UpdateEventById(id,status);
            if (iret>0)
            {
                return ApiResponse<int>.SuccessResult(iret, "更新成功");
            }
            return ApiResponse<int>.ErrorResult("更新失败");
           
        }


    }
}
